/**
 * $Id$ Copyright 2009-2012 Oak Pacific Interactive. All rights reserved.
 */
package com.shuqi.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.EditTextLengthFilter;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.utils.CheckInputUtils;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.AccountBindController;
import com.shuqi.controller.ControllerBase;
import com.shuqi.controller.FindPasswordController;
import com.shuqi.controller.MainController;
import com.shuqi.controller.R;
import com.shuqi.database.dao.impl.AccountDao;
import com.shuqi.database.model.UserInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.manager.MyAccountManager;
import com.shuqi.model.net.listener.HttpRequestErrListener;
import com.shuqi.model.parse.parser.AccountBindParser.AccountBindParserInfo;
import com.shuqi.model.parse.parser.PasswordSettingParser.PasswordSettingParserInfo;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 
 * @author <a href="mailto:">yaozhen</a>
 * @version 2014-2-11下午4:10:00
 */
public class PasswordSettingActivity extends ActivityBase implements OnClickListener,
        IEventListener, HttpRequestErrListener {

    public static final String INTENT_PAGE_TYPE = "intent_page_type";

    public static final String INTENT_ACCOUNT_TYPE = "intent_account_type";

    public static final String INTENT_PHONENUMBER = "intent_phone_number";

    public static final String INTENT_PHONE_VERIFYCODE = "intent_phone_verify_code";

    public static final int TYPE_FIND_PASSWORD_BYPHONE = 100; // 找回密码

    public static final int TYPE_BINDACCOUNT_BYPHONE = 101; // 绑定手机

    private EditText mPwdEditText;

    private ControllerBase mController;

    private ImageView mVisibleImg;

    private ToastDialog mLoadingDialog;

    private TextView mPwdPointTextView;

    private int mPageType;

    private int mAccountType;

    private String mPhoneNumber;

    private String mVerifyCode;

    private boolean mIsVisible = false;

    private String mCurPwd;
    private CommonTitle mTitle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_account_passwordsetting);
        handlerIntent();
        initView();
        if (mPageType == TYPE_FIND_PASSWORD_BYPHONE) {
            mController =
                    (FindPasswordController) MainController.getMainManagerInstance()
                            .createController(MainController.CONTROLLER_ID_FINDPASSWORD, this);
            StatisticsUtils
                    .onEvent(StatisticsEventID.ACCOUNT_FINDPASSWORD_BYMOBILE_ENTEER_SETTINGPASSWORD);
        } else if (mPageType == TYPE_BINDACCOUNT_BYPHONE) {
            mController =
                    (AccountBindController) MainController.getMainManagerInstance()
                            .createController(MainController.CONTROLLER_ID_ACCOUNT_BINDPHONE, this);
            StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_BIND_MOBILE_PASSWORD_PAGE_ENTER);
        }

        mController.addEventListener(this);
        // 默认密文
        mPwdEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        InputFilter[] filters = {new EditTextLengthFilter(16)};
        mPwdEditText.setFilters(filters);
    }

    private void handlerIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            mPageType = intent.getIntExtra(INTENT_PAGE_TYPE, 0);
            mPhoneNumber = intent.getStringExtra(INTENT_PHONENUMBER);
            if (intent.hasExtra(INTENT_ACCOUNT_TYPE)) {
                mAccountType = intent.getIntExtra(INTENT_ACCOUNT_TYPE, 0);
            }
            if (intent.hasExtra(INTENT_PHONE_VERIFYCODE)) {
                mVerifyCode = intent.getStringExtra(INTENT_PHONE_VERIFYCODE);
            }
        }
    }

    private void initView() {
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);
        findViewById(R.id.complete_ok).setOnClickListener(this);
        mPwdEditText = (EditText) findViewById(R.id.edit_password);
        mVisibleImg = (ImageView) findViewById(R.id.img_visible);
        mPwdPointTextView = (TextView) findViewById(R.id.pwd_point);
        mVisibleImg.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.complete_ok:
                StatisticsUtils.onEvent(StatisticsEventID.ACCOUNT_FINDPASSWORD_BYMOBILE_COMPLETE_CLICK);
                clickComplete();
                break;
            case R.id.img_visible:
                clickVisibleImg();
                break;
            default:
                break;
        }
    }

    private void clickVisibleImg() {
        mIsVisible = !mIsVisible;
        int rId = mIsVisible ? R.drawable.password_visible : R.drawable.password_invisible;
        mVisibleImg.setImageResource(rId);
        if (mIsVisible) {
            mPwdEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            mPwdEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        String msg = mPwdEditText.getText().toString();
        if (!TextUtils.isEmpty(msg)) {
            mPwdEditText.setSelection(msg.length());
        }
    }

    private void clickComplete() {
        String pwd = mPwdEditText.getText().toString();
        boolean isPwd = CheckInputUtils.checkPassword(pwd, mPwdPointTextView);
        if (!isPwd) {
            return;
        }
        Util.hidesoftkeyboard(getApplicationContext(), mPwdEditText);

        if (mPageType == TYPE_FIND_PASSWORD_BYPHONE) {
            mController.handle(FindPasswordController.EVENT_TYPE_FINDPWDBYPHONE, mPhoneNumber, pwd,
                    mVerifyCode);
            showLoadingDialog(true, false, "正在找回密码");
        } else if (mPageType == TYPE_BINDACCOUNT_BYPHONE) {
            mCurPwd = pwd;
            ((AccountBindController) mController).bind(mPhoneNumber, pwd, mAccountType,
                    mVerifyCode, null);
            showLoadingDialog(true, false, "正在绑定");
            StatisticsUtils
                    .onEvent(StatisticsEventID.ACCOUNT_BIND_MOBILE_PASSWORD_PAGE_COMPLETE_CLICK);
        }
    }

    private void showLoadingDialog(boolean isLoading, boolean isSuccess, String showText) {
        if (isFinishing()) {
            return;
        }
        if (mLoadingDialog == null) {
            mLoadingDialog = new ToastDialog(this);
            mLoadingDialog.setDissmisOnClickOutSide(false);
        }
        if (isLoading) {
            mLoadingDialog.loading(showText);
            return;
        }
        mLoadingDialog.setDissmisOnClickOutSide(true);
        mLoadingDialog.show(isSuccess, showText);

    }

    private void hideLoadingDialog() {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                if (mLoadingDialog != null) {
                    mLoadingDialog.dismiss();
                }
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }

    @Override
    public void activityLogicForward() {

    }

    @Override
    public void activityInitData() {

    }

    @Override
    public void onEvent(int event, final Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                Runnable r = new Runnable() {

                    @Override
                    public void run() {
                        onNetworkCallback(data);
                    }
                };
                ShuqiApplication.getApplicationHandler().post(r);
                break;

            default:
                hideLoadingDialog();
                showMsg("网络连接超时");
                break;
        }

    }

    private void onNetworkCallback(Object data) {
        if (mPageType == TYPE_FIND_PASSWORD_BYPHONE) {
            hideLoadingDialog();
            PasswordSettingParserInfo info = (PasswordSettingParserInfo) data;
            String msg = info.message;
            if (!TextUtils.isEmpty(msg)) {
                showMsg(msg);
            }
            if (info.resultCode == 200) {
                // 成功
                gotoLoginActivity();
            }

        } else if (mPageType == TYPE_BINDACCOUNT_BYPHONE) {

            AccountBindParserInfo info = (AccountBindParserInfo) data;
            String msg = info.message;
            if (!TextUtils.isEmpty(msg)) {
                showMsg(msg);
            }
            if (info.resultCode == 200) {
                // 存入数据库
                updateUserInfoToDB(info);
                // goto account页面
                hideLoadingDialog();
//                gotoAccountActivity();
                gotoAccountBindActivity();
            }
            // else {
            // 失败
            // showLoadingDialog(false, false, "绑定失败");
            // }
        }
    }

    private void gotoLoginActivity() {
        LoginActivity.openVerifyForResult(this, LoginActivity.LOGINTYPE_LOGIN);
    }

    /** 回到绑定界面 */
    private void gotoAccountBindActivity() {
        AccountActivity.callRefreshAccountOnResume();
        Intent intent = new Intent(this, AccountBindActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        ActivityManager.getInstance().startNextActivity(intent, this);
    }

    /**
     * 
     * @param info 存入最新的用户信息
     */
    private void updateUserInfoToDB(AccountBindParserInfo info) {
        UserInfo user = MyAccountManager.getInstance(getApplicationContext());
        if (user == null) {
            return;
        }
        if (!TextUtils.isEmpty(mPhoneNumber)) {
            user.setMobile(mPhoneNumber);

        }
        if (!TextUtils.isEmpty(info.session)) {
            user.setSession(info.session);
        }
        if (!TextUtils.isEmpty(mCurPwd)) {
            user.setPassword(mCurPwd);
        }

        AccountDao.getInstance().saveUserInfo(user);
        // UserInfoHelper.insertOrUpdateUserInfo(getApplicationContext(), user);
    }

    @Override
    public void request_content_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_reponse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_format() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_net_error() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_timeout() {}

    @Override
    public void request_url() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
        mController.onDestroy();
    }

    /**
     * 
     * @param context
     * @param pageType 页面类型 100 找回密码 101 绑定手机
     * @param accountType 账户类型 (1表示绑定手机号 2表示绑定Email 3表示绑定新浪微博) 常量定义在AccountBindModel中
     * @param phoneNumber 手机号
     */
    public static void show(Activity context, int pageType, int accountType, String phoneNumber,
            String verifyCode) {
        Intent intent = new Intent(context, PasswordSettingActivity.class);
        intent.putExtra(INTENT_PAGE_TYPE, pageType);
        intent.putExtra(INTENT_ACCOUNT_TYPE, accountType);
        intent.putExtra(INTENT_PHONENUMBER, phoneNumber);
        intent.putExtra(INTENT_PHONE_VERIFYCODE, verifyCode);
        ActivityManager.getInstance().startNextActivity(intent, context);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
